package com.hengxinguotong.hxgtwygsp.ui.main.video;

import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.hengxinguotong.hxgtwygsp.R;
import com.hengxinguotong.hxgtwygsp.model.Video;
import com.hengxinguotong.hxgtwygsp.ui.base.BaseFragment;
import com.hengxinguotong.hxgtwygsp.ui.base.BaseViewHolder;
import com.hengxinguotong.hxgtwygsp.utils.CommUtil;
import com.hengxinguotong.hxgtwygsp.widget.RecycleViewDivider;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;

public class VideoFragment extends BaseFragment implements VideoContract.IView, SurfaceHolder.Callback {

    @Inject
    VideoPresenter mPresenter;
    @BindView(R.id.video_surface)
    SurfaceView videoSurface;
    @BindView(R.id.video_hander)
    CheckBox videoHander;
    @BindView(R.id.video_hander_container)
    LinearLayout videoHanderContainer;
    @BindView(R.id.video_recycler)
    RecyclerView videoRecycler;

    @BindView(R.id.video_up)
    ImageView mVideoUp;
    @BindView(R.id.video_down)
    ImageView mVideoDown;

    private List<Video> videoList;
    private VideoAdapter videoAdapter;
    private int currentIndex = 0;
    private boolean isCompleted = false;
    private boolean mIsVisibleToUser;

    @Inject
    public VideoFragment() {
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mPresenter.bindView(this);
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        mIsVisibleToUser = isVisibleToUser;
        if (isVisibleToUser) {
            if (isCompleted && videoList.size() > 0) {
                currentIndex = videoList.size() > (currentIndex + 1) ? currentIndex + 1 : 0;
                isCompleted = false;
                videoAdapter.notifyDataSetChanged();
                mPresenter.prepare(videoList.get(currentIndex));
            }
            mPresenter.start();
        } else {
            mPresenter.pause();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        mPresenter.pause();
    }


    @Override
    public void onResume() {
        if (mIsVisibleToUser) {
            mPresenter.start();
        }
        super.onResume();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mPresenter.dropView();
    }

    @Override
    public int getLayoutResId() {
        return R.layout.fragment_video;
    }

    @Override
    public void init()
    {
        SurfaceHolder holder = videoSurface.getHolder();
        holder.addCallback(this);
        LinearLayoutManager llm = new LinearLayoutManager(getContext());
        llm.setOrientation(LinearLayoutManager.VERTICAL);
        videoRecycler.setLayoutManager(llm);
        videoRecycler.addItemDecoration(new RecycleViewDivider(getContext()).height(getResources().getDimensionPixelSize(R.dimen.px_10)));
        videoList = new ArrayList<>();
        for (int i = 0; i < 11; i++) {
            videoList.add(new Video(i+".mp4"));
        }
        videoAdapter = new VideoAdapter();
        videoRecycler.setAdapter(videoAdapter);
        mPresenter.initAnimator(videoHanderContainer);
    }

    @OnClick({R.id.video_up, R.id.video_down, R.id.video_hander})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.video_up:
                if (videoList != null&& videoList.size()>0) {
                    LinearLayoutManager layoutManager = (LinearLayoutManager) videoRecycler.getLayoutManager();
                    int firstPosition = layoutManager.findFirstCompletelyVisibleItemPosition();
                    videoRecycler.scrollToPosition(firstPosition>0?firstPosition-1:0);
                }
                break;
            case R.id.video_down:
                if (videoList != null&& videoList.size()>0) {
                    LinearLayoutManager layoutManager = (LinearLayoutManager) videoRecycler.getLayoutManager();
                    int lastPosition = layoutManager.findLastCompletelyVisibleItemPosition();
                    videoRecycler.scrollToPosition(lastPosition<videoList.size()-1?lastPosition+1:videoList.size()-1);
                }
                break;
            case R.id.video_hander:
                if (videoHander.isChecked()) {
                    mPresenter.showAnimator();
                } else {
                    mPresenter.dismissAnimator();
                }
                break;
        }
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        mPresenter.initMediaPlayer(holder);
        if (videoList != null && videoList.size() > 0) {
            Video video = videoList.get(0);
            mPresenter.prepare(video);
//            mPresenter.start();
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {

    }

    @Override
    public void updateHanderStatus() {
        videoHander.setChecked(false);
    }

    @Override
    public void updateCompleted() {
        isCompleted = true;

        // TODO: 循环播放
        if (isCompleted && videoList.size() > 0) {
            currentIndex = videoList.size() > (currentIndex + 1) ? currentIndex + 1 : 0;
            isCompleted = false;
            videoAdapter.notifyDataSetChanged();
            mPresenter.prepare(videoList.get(currentIndex));
        }
        mPresenter.start();
    }

    public class VideoHolder extends BaseViewHolder<Integer> {
        @BindView(R.id.video_image)
        ImageView videoImage;

        private int padding = getResources().getDimensionPixelSize(R.dimen.px_1);



        public VideoHolder(View itemView) {
            super(itemView);
            videoImage.setOnClickListener(videoAdapter);
        }

        @Override
        public void bindData(Integer integer) {
            if (integer == currentIndex) {
                videoImage.setPadding(padding, padding, padding, padding);
            } else {
                videoImage.setPadding(0, 0, 0, 0);
            }
            Uri imageUri = Uri.parse(CommUtil.getDataDir(getContext()) + File.separator + integer+".JPG");

            videoImage.setImageURI(imageUri);
            videoImage.setTag(integer);
        }
    }

    public class VideoAdapter extends RecyclerView.Adapter<VideoHolder> implements View.OnClickListener {
        @NonNull
        @Override
        public VideoHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = View.inflate(getContext(), R.layout.item_video, null);
            return new VideoHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull VideoHolder holder, int position) {
            holder.bindData(position);
        }

        @Override
        public int getItemCount() {
            return videoList.size();
        }

        @Override
        public void onClick(View v) {
            int index = (int) v.getTag();
            if (currentIndex == index) {
                return;
            }
            currentIndex = index;
            notifyDataSetChanged();
            Video video = videoList.get(currentIndex);
            mPresenter.prepare(video);
            mPresenter.start();
            mPresenter.recoverRemainTime();
        }
    }
}
